package org.yan.kangaroo.storage.service.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yan.kangaroo.common.util.McpStringUtils;
import org.yan.kangaroo.storage.config.AliyunOssConfig;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 阿里云Oss访问客户端
 *
 * @author wangx 2020/05/29 16:37
 */
@Component
@Slf4j
public class OssObjectResourceClient {
    private final AliyunOssConfig aliyunOssConfig;


    public OssObjectResourceClient(AliyunOssConfig aliyunOssConfig) {
        this.aliyunOssConfig = aliyunOssConfig;
    }


    public String uploadObject(File file) {
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(),
                aliyunOssConfig.getAccessKeyId(),
                aliyunOssConfig.getAccessKeySecret());
        LocalDate now = LocalDate.now();
        String date = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String key = date + File.separator + file.getName();
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssConfig.getBucket(), key, file);
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        log.info("[uploadFile] 上传成功, result:{}", putObjectResult);
        ossClient.shutdown();
        return key;
    }

    public String uploadFile(InputStream inputStream, String fileName, String contentType) {
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(),
                aliyunOssConfig.getAccessKeyId(),
                aliyunOssConfig.getAccessKeySecret());
        LocalDate now = LocalDate.now();
        String date = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String key = date + "/" + McpStringUtils.getUuid() + "/" + fileName;
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(contentType);
        PutObjectResult result = ossClient.putObject(aliyunOssConfig.getBucket(), key, inputStream, metadata);
        log.info("[uploadFile] result:{}", result);
        ossClient.shutdown();
        return key;
    }

    public InputStream getFile(String key) {
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(),
                aliyunOssConfig.getAccessKeyId(),
                aliyunOssConfig.getAccessKeySecret());
        OSSObject ossObject = ossClient.getObject(aliyunOssConfig.getBucket(), key);
        return ossObject.getObjectContent();
    }

}
